﻿using SheepStorage.Domain.DTO.Output;
using SheepStorage.Domain.Entity;
using SheepStorage.Repository.Interface;
using SheepStorage.Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace SheepStorage.Service.DataImp
{
    /// <summary>
    /// 种母分娩实现
    /// </summary>
    public class SheepMomDeliveryService : ISheepMomDeliveryService
    {
        private readonly IBaseRepository<SheepMomDelivery> delivery;
        private readonly IBaseRepository<BuildingManagement> management;
        private readonly IBaseRepository<SheepField> sheepfield;
        private readonly IBaseRepository<SheepRecord> record;
        private readonly IBaseRepository<EarTagTable> eartag;
        private readonly IBaseRepository<SheepMomHistory> history;
        private readonly IBaseRepository<SheepChangeDormitory> dormitory;
        public SheepMomDeliveryService(IBaseRepository<SheepMomDelivery> delivery, IBaseRepository<BuildingManagement> management,
            IBaseRepository<SheepField> sheepfield, IBaseRepository<SheepRecord> record, IBaseRepository<EarTagTable> eartag,
            IBaseRepository<SheepMomHistory> history, IBaseRepository<SheepChangeDormitory> dormitory)
        {
            this.delivery = delivery;
            this.management = management;
            this.sheepfield = sheepfield;
            this.record = record;
            this.eartag = eartag;
            this.history = history;
            this.dormitory = dormitory;
        }
        /// <summary>
        /// 种母分娩显示
        /// </summary>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="OverBit">耳号</param>
        /// <param name="MomPergnantPrincipal">负责人</param>
        /// <param name="BuildingManagementId">转出栋舍</param>
        /// <param name="DeliverySlowId">窝号</param>
        /// <returns></returns>
        public async Task<List<SheepMomDeliveryDto>> GetSheepMomDelivery(string? startTime, string? endTime, string? OverBit, string? MomPergnantPrincipal, int BuildingManagementId, string? DeliverySlowId)
        {
            var list = (from delivery in delivery.GetAll()
                        join management in management.GetAll()
                        on delivery.BuildingManagementId equals management.BuildingManagementId into mg
                        from management in mg.DefaultIfEmpty()
                        join sheepfield in sheepfield.GetAll()
                        on delivery.SheepFieldId equals sheepfield.SheepFieldId into sf
                        from sheepfield in sf.DefaultIfEmpty()
                        where delivery.IsDel == 1
                         && (string.IsNullOrWhiteSpace(startTime) || delivery.MomDeliveryDate <= DateTime.Parse(startTime))
                          && (string.IsNullOrWhiteSpace(endTime) || delivery.MomDeliveryDate >= DateTime.Parse(endTime))
                          && (string.IsNullOrWhiteSpace(OverBit) || delivery.OverBit.Contains(OverBit))
                           && (string.IsNullOrWhiteSpace(MomPergnantPrincipal) || delivery.DeliveryPrincipal == MomPergnantPrincipal)
                           && (string.IsNullOrWhiteSpace(DeliverySlowId) || delivery.DeliverySlowId == DeliverySlowId)
                           && (BuildingManagementId == 0 || delivery.BuildingManagementId == BuildingManagementId)
                        select new SheepMomDeliveryDto()
                        {
                            DeliveryPrincipal = delivery.DeliveryPrincipal,
                            DeliveryAuditor = delivery.DeliveryAuditor,
                            AddName = delivery.AddName,
                            AddTime = delivery.AddTime,
                            DeliveryAuditorDate = delivery.DeliveryAuditorDate,
                            DeliveryDieAvgWeight = delivery.DeliveryDieAvgWeight,
                            DeliveryDieSumWeight = delivery.DeliveryDieSumWeight,
                            DeliveryDocuument = delivery.DeliveryDocuument,
                            DeliveryFatSheep = delivery.DeliveryFatSheep,
                            DeliveryHealth = delivery.DeliveryHealth,
                            DeliveryLivingAvgWeight = delivery.DeliveryLivingAvgWeight,
                            DeliveryLivingSumWeight = delivery.DeliveryLivingSumWeight,
                            DeliveryMalformation = delivery.DeliveryMalformation,
                            DeliveryMonster = delivery.DeliveryMonster,
                            DeliveryMummy = delivery.DeliveryMummy,
                            DeliveryRemark = delivery.DeliveryRemark,
                            DeliverySex = delivery.DeliverySex,
                            DeliverySlowId = delivery.DeliverySlowId,
                            DeliveryStillbirth = delivery.DeliveryStillbirth,
                            DeliveryTotalDie = delivery.DeliveryTotalDie,
                            DeliveryTotalLiving = delivery.DeliveryTotalLiving,
                            DeliveryTotalWeight = delivery.DeliveryTotalWeight,
                            DeliveryWeak = delivery.DeliveryWeak,
                            DelName = delivery.DelName,
                            DelTime = delivery.DelTime,
                            IsDel = delivery.IsDel,
                            MomDeliveryComplexity = delivery.MomDeliveryComplexity,
                            MomDeliveryCount = delivery.MomDeliveryCount,
                            MomDeliveryDate = delivery.MomDeliveryDate,
                            MomDeliveryGestation = delivery.MomDeliveryGestation,
                            MomDeliveryId = delivery.MomDeliveryId,
                            MomDeliveryLactation = delivery.MomDeliveryLactation,
                            MomDeliveryMastitis = delivery.MomDeliveryMastitis,
                            MomDeliveryMaternity = delivery.MomDeliveryMaternity,
                            OverBit = delivery.OverBit,
                            PurchaseSerialNumber = delivery.PurchaseSerialNumber,
                            Remarks = delivery.Remarks,
                            UpdateName = delivery.UpdateName,
                            UpdateTime = delivery.UpdateTime,

                            BuildingManagementId = delivery.BuildingManagementId,
                            BuildingManagementIdName = management.BuildingName,

                            DeliveryBuilding = delivery.DeliveryBuilding,
                            DeliveryField = delivery.DeliveryField,

                            SheepFieldId = delivery.SheepFieldId,
                            SheepFieldIdName = sheepfield.SheepFieldName,
                        }).ToList();
            var listt = list;
            return listt;
        }
        /// <summary>
        /// 种母分娩添加
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>

        public async Task<int> AddSheepMomDelivery(List<SheepMomDelivery> sheepMomDelivery)
        {
            foreach (var m in sheepMomDelivery)
            {
                //雪花Id赋值单据号
                m.DeliveryDocuument = YitIdHelper.NextId().ToString();
                //雪花Id赋值流水号
                m.PurchaseSerialNumber = YitIdHelper.NextId().ToString();
                m.AddName = "张新祥";
                m.AddTime = DateTime.Now;
                m.IsDel = 1;

                var lists = record.GetAll().FirstOrDefault(s => s.SheepRecordId == int.Parse(m.OverBit));
                m.OverBit = lists.OverBit;
                var result = delivery.Add(m);
                if (result > 0)
                {
                    if (m.OverBit != null)
                    {
                        var list = record.GetAll().FirstOrDefault(s => s.SheepRecordId == lists.SheepRecordId);
                        list.SheepRecordBreedState = 8;
                        list.SheepRecordGestation = 1;
                        list.BuildingName = management.GetAll().FirstOrDefault(x => x.BuildingManagementId == m.BuildingManagementId).BuildingName;
                        list.SheepFieldName = sheepfield.GetAll().FirstOrDefault(x => x.SheepFieldId == m.SheepFieldId).SheepFieldName;
                        record.Update(list);

                        var his = history.GetAll().FirstOrDefault(s => s.OverBit == m.OverBit);
                        his.MomHistoryDeliveryDate = m.MomDeliveryDate;
                        his.MomDeliveryMalformation = m.DeliveryMalformation;
                        his.MomDeliveryMonster = m.DeliveryMonster;
                        his.MomDeliveryMummy = m.DeliveryMummy;
                        his.MomDeliveryStillbirth = m.DeliveryStillbirth;
                        his.MomDeliveryWeak = m.DeliveryWeak;
                        his.MomHistoryHealth = m.DeliveryHealth;
                        his.MomHistoryHealthWeight = m.DeliveryTotalWeight;
                        history.Update(his);
                        var sheepChangeDormitory = new SheepChangeDormitory()
                        {
                            AddName = "王小小",
                            AddTime = DateTime.Now,
                            OverBit = m.OverBit,
                            ChangedormitoryType = 3,
                            DocumentNumber = YitIdHelper.NextId().ToString(),
                            ElEarTag = m.OverBit,
                            IsDel = 0,
                            SerialNumber = YitIdHelper.NextId().ToString(),
                            SheepSex = m.DeliverySex,
                            SheepType = 1,
                            RollOutField = m.DeliveryField,
                            TransferOutDormitory = m.DeliveryBuilding,
                            Auditor = null,
                            AuditTime = null,
                            ChangeRemark = null,
                            DelName = null,
                            DelTime = null,
                            Remarks = null,
                            UpdateName = null,
                            UpdateTime = null,
                            ChangedormitoryDate = DateTime.Now,
                            ChangeState = 0,
                            DriveField = m.SheepFieldId,
                            TransferToDormitory = m.BuildingManagementId,
                            Variety = eartag.GetAll().FirstOrDefault(s => s.OverBit == m.OverBit).BirType,
                        };
                        dormitory.Add(sheepChangeDormitory);
                    }
                }
            }
           
            return 1;
        }
        /// <summary>
        /// 种母分娩信息删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<int> DelSheepMomDelivery(int id)
        {
            var list = delivery.GetInfoBy(id);
            list.IsDel = 0;
            list.DelName = "王小小";
            list.DelTime = DateTime.Now;
            return delivery.Update(list);
        }
        /// <summary>
        /// 种母分娩信息反填
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<SheepMomDelivery> BackFillSheepMomDelivery(int id)
        {
            var list = delivery.GetInfoBy(id);
            return list;
        }
        /// <summary>
        /// 修改种母分娩信息
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public async Task<int> UpdateSheepMomDelivery(SheepMomDelivery m)
        {
            m.UpdateName = "管理人";
            m.UpdateTime = DateTime.Now;
            return delivery.Update(m);
        }
        /// <summary>
        /// 分娩全部 图表显示
        /// </summary>
        /// <returns></returns>
        public object GetSheepMomDeliveryList()
        {
            var list = delivery.GetAll().Where(c => c.IsDel == 1).ToList();
            var groupList = list.GroupBy(c => c.MomDeliveryDate.Value.Month).ToList();
            var countList = groupList.Select(g => new
            {
                month = g.Key, // g.Key 是月份值
                countHealth = g.Sum(c => c.DeliveryHealth),//健羔数
                countWeak = g.Sum(c => c.DeliveryWeak),//弱羔数
                countMalformation = g.Sum(c => c.DeliveryMalformation), //畸形数
                countStillbirth = g.Sum(c => c.DeliveryStillbirth), //死胎数
                countMonster = g.Sum(c => c.DeliveryMonster), //畸胎数
                countMummy = g.Sum(c => c.DeliveryMummy),//木乃伊数
                countMomDelivery = g.Sum(c => c.DeliveryHealth+c.DeliveryWeak+c.DeliveryMalformation+c.DeliveryStillbirth+c.DeliveryMonster+c.DeliveryMummy) //产羔总数
                // 如果需要获取每个月份对应的具体记录列表，可以进一步操作 g.ToList()
            }).ToList();
            // 如果需要返回一个包含月份和对应记录的结果列表，可以进行适当的修改
            return countList;
        }


    }

}
